import { useEffect, useMemo, useRef, useState } from 'react';
import { ActionType, EditableProTable, PageContainer, ProColumns, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Button, message, Select, Spin, Upload } from 'antd';
import { useRequest } from 'ahooks';
import { uploadCourse, getCrew, allCrewServices, courseAllocation } from '@/services/supervisionApi';
import { request, useModel } from '@umijs/max';
import ColumnGroup from 'antd/es/table/ColumnGroup';
import CrewInfoModel from './components/CrewInfoPop';
import React from 'react';

interface Course {
    id: Number;
    classroomLocation: string;
    // 其他字段...
}

type DataSourceType = {
    id: React.Key;
    title?: string;
    readonly?: string;
    decs?: string;
    state?: string;
    created_at?: number;
    update_at?: number;
    children?: DataSourceType[];
  };

export default function SupervisionCoursePage() {
    const [crewInfo, setAllCrewInfo] = useState([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [popVisible, setPopVisible] = React.useState(false);
    const [detail, setDetail] = React.useState(null);

    const allCrewInfo = useRequest(allCrewServices, {
        manual: true,
        onSuccess: (data) => {
            console.log("data", data);
            setAllCrewInfo(data)
            setLoading(false)
        }
    })

    useEffect(() => {
        allCrewInfo.run()
    }, [])

    const submitCourseAllocation = useRequest(courseAllocation, {
        manual: true,
        onSuccess: (data: any) => {
            console.log("data", data);
        }
    })

    const selectChange = (value: string, record: Course) => {
        console.log('Selected value:', value);
        console.log('Record:', record);
        // 在这里处理选择变化的逻辑
        submitCourseAllocation.run({ crewId: value, courseId: String(record.id) })
    };

    // 自定义排序函数
    const customSorter = (a: Course, b: Course) => {
        // 提取房间号和前缀
        const extractRoomNumber = (location: string) => {
            const match = location.match(/([a-zA-Z]+)(\d+)/);
            if (match) {
                return { prefix: match[1], number: parseInt(match[2], 10) };
            }
            return { prefix: '', number: 0 };
        };

        const aRoom = extractRoomNumber(a.classroomLocation);
        const bRoom = extractRoomNumber(b.classroomLocation);

        // 首先按前缀排序
        if (aRoom.prefix !== bRoom.prefix) {
            return aRoom.prefix.localeCompare(bRoom.prefix);
        }

        // 如果前缀相同，按数字排序
        return aRoom.number - bRoom.number;
    };

    const columns = useMemo<ProColumns[]>(
        () => [
            {
                title: 'id',
                dataIndex: 'id',
                key: 'college',
                hideInSearch: true,
                width: 70,
            },
            {
                title: "上课地点",
                dataIndex: 'classroomLocation',
                key: 'course',
                hideInSearch: true,
                width: 200,
                sorter: customSorter,
            },
            {
                title: '开课课程',
                dataIndex: 'courseName',
                key: 'selectCourse',
                hideInSearch: true,
                width: 200,
            },
            {
                title: '上课班级',
                dataIndex: 'classRoom',
                key: 'selectCourse',
                hideInSearch: true,
                width: 320,
            },
            {
                title: '授课教师',
                dataIndex: 'teacher',
                key: 'selectCourse',
                hideInSearch: true,
            },
            {
                title: "分配教室",
                dataIndex: 'crews',
                key: 'crews',
                tooltip: "只要在你为组员分配教师 之后 组员才有记录",
                hideInSearch: true,
                valueType: 'select',
                valueEnum: {
                    all: { text: '全部', status: 'Default' },
                    open: {
                        text: '未解决',
                        status: 'Error',
                    },
                    closed: {
                        text: '已解决',
                        status: 'Success',
                    },
                },
            },
            {
                title: '操作',
                valueType: 'option',
                key: 'option',
                render: (_: any, record: any) => [
                    <Button
                        type="link"
                        size='middle'
                        onClick={() => {
                            setDetail({ ...record })
                            setPopVisible(true)
                        }}
                    >
                        详情
                    </Button>,
                ],
            },
        ],
        [false],
    );

    const actionRef = useRef<ActionType>();

    return (
        <PageContainer title="组员管理">
            <Spin spinning={loading}>
                <ProTable
                    columns={columns}
                    actionRef={actionRef}
                    rowKey="id"
                    options={{ fullScreen: true, density: true, setting: true }}
                    request={
                        (params, sort) => getCrew()
                    }
                    toolBarRender={() => [
                        <Button type="primary">获取课表</Button>,
                        <Button type="primary">导出图片</Button>
                    ]}
                />
            </Spin>

            <CrewInfoModel
                data={detail}
                open={popVisible}
                onOpenChange={(_open: boolean) => {
                    setPopVisible(_open)
                    if (!_open) {
                        setDetail(null)
                    }
                }}
                onFinish={() => {
                    setPopVisible(false);
                    (actionRef?.current as any)?.reload()
                }}
            />
        </PageContainer>
    );

}

